package com.turtle.security.security.config;

import com.turtle.security.security.filter.AuthenticationTokenFilter;
import com.turtle.security.security.handle.AuthenticationFailHandle;
import com.turtle.security.security.handle.LogoutSuccessHandle;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置
 *
 * @author turtle
 * date: 2020-05-04
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthenticationFailHandle unauthorizedHandler;
    private final UserDetailsService userDetailsService;
    private final AuthenticationTokenFilter authenticationTokenFilter;
    private final LogoutSuccessHandle logoutSuccessHandle;

    /**
     * 解决无法直接注入 AuthenticationManager问题
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            // 认证失败处理类
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // 无状态模式
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            // 接口相关
            .antMatchers(
                "/security/auth/login",
                "/security/auth/register"
            ).permitAll()
            .anyRequest().authenticated()
            .and()
            .headers().frameOptions().disable();
        // 添加token filter
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 退出登录处理
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandle);
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        // swagger相关静态资源跳过过滤器
        webSecurity
            .ignoring()
            .antMatchers(
                HttpMethod.GET,
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "/favicon.ico",
                "/*/api-docs",
                "/swagger-resources/**",
                "/webjars/**",
                "/users/user/login"
            );
    }

    /**
     * 密码加密
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份验证
     *
     * @param authenticationManager
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder authenticationManager) throws Exception {
        authenticationManager.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}
